package Clases;

import java.net.*;
import java.io.*;
import java.util.*;

public class Chat {
    
    private static ServerSocket ss;
	private static boolean encontrado;

	public static void main(String[] args) {
	try
	    {
		Vector<PrintStream> clients = new Vector<PrintStream>();
		
		boolean NotTaken=true;
		String[] nicknames=new String[100];
		int k=0;
	        boolean asunto=false;
		setEncontrado(false);
		String sujet="";
		System.out.println("Serveur initie ...");
		ss = new ServerSocket(8777);
		while (true)
		    {
			
			Socket socket = ss.accept();
			//get input and output streams and advanced streams
			OutputStream os=socket.getOutputStream();
			InputStream is=socket.getInputStream();
			PrintWriter out=new PrintWriter(os,true);
			BufferedReader in=new BufferedReader(new InputStreamReader(is));
			
			
			//gestion des messages HELLO
			
			String receivedString=in.readLine();
			System.out.println(receivedString);
			StringTokenizer word=new StringTokenizer(receivedString);
			String firstWord=word.nextToken();
			
			if (firstWord.equals("HELLO"))
			    {
				
				String secondWord=word.nextToken();
				System.out.println("Le nick recu est" + secondWord); 
				
				//on verifie si le nick est deja utilise
				NotTaken=true;
				for (int i=0;i<100; i++)
				    {
					if(secondWord.equals(nicknames[i]))
					    {
						i=100;
						System.out.println("Le nick est deja pris:" + secondWord);
						//le nick est pris,on repond HELLO NOK et on ferme la connexion
						out.println("HELLO NOK");
						socket.close();
						NotTaken=false;
					    }
				    }
				
				//sinon, on repond HELLO OK et on ajoute l'usager a la session
				if (NotTaken)
				    {
					nicknames[k]=secondWord;
					k++;
					System.out.println("On envoie HELLO OK a " + secondWord);
					out.println("HELLO OK");
					//Si on n'a oas un sujet, on envoie "Asunto" a l'usager pour qu'il ajoute un
					if(asunto==false){
					    out.println("Asunto");
					    sujet=in.readLine();
					    asunto=true;
					    System.out.println("Le sujet de ce chat est maintenant : " + sujet); 
					}
					else
					    out.println("Le sujet de ce chat est: " + sujet);
					new ChatThread(socket,clients,secondWord).start();
				    } 
			    }
		    }    
	    }catch (Exception e)
		{
		    e.printStackTrace();
		}
    }

	public static boolean isEncontrado() {
		return encontrado;
	}

	public static void setEncontrado(boolean encontrado) {
		Chat.encontrado = encontrado;
	}
}